import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_svg/flutter_svg.dart' as svg;
import 'package:get/get.dart';
import 'package:hixing_app/assets/r_img.dart';
import 'package:hixing_app/views/test_view/canvas_utils.dart';
import 'package:hixing_app/views/test_view/reset_test_matrix4/model/action_picture.dart';
import 'package:hixing_app/views/test_view/reset_test_matrix4/model/matrix4_data_model.dart';
import 'package:hixing_app/views/test_view/reset_test_matrix4/model/matrix_compose_model.dart';
import 'package:hixing_app/views/test_view/test_matrix4/rect_element_model.dart';
import 'package:hixing_app/views/test_view/test_matrix4/transform_vertex_model.dart';
import 'package:hixing_app/widgets/toast/toast.dart';
import 'package:vector_math/vector_math_64.dart' as vector;
import 'dart:math' as math;

import 'model/matrix4_data_compose_model.dart';

class MatrixToCompose extends StatefulWidget {
  @override
  _MatrixToComposeState createState() => _MatrixToComposeState();
}

class _MatrixToComposeState extends State<MatrixToCompose> {
  List<ActionPicture> actionPictureList = [];

  ActionPicture get currentActionPture => composeData == null
      ? actionPictureList[currentIndex]
      : composeData!.composePictureData!;
  int currentIndex = 0;

  // 触摸开始的点的数据
  Offset startPosition = const Offset(0, 0);

  List<svg.PictureInfo> iconSvgLockList = [];
  List<svg.PictureInfo> iconSvgUnLockList = [];
  MatrixComposeModel? composeData;

  // 当前操作事件
  CanvasEventType? eventType;

  Future<void> loadImg() async {
    var pgSvg = await rootBundle.loadString(ImgR.imgBgPguinSVG);
    final svg.PictureInfo pictureInfo1 = await svg.vg.loadPicture(
        svg.SvgStringLoader(
          pgSvg,
        ),
        null);
    //初始化对象
    ActionPicture actionPicture =
        ActionPicture.initActionPicture(initImgSvgPicture: pictureInfo1);
    actionPictureList.add(actionPicture);
  }

  Future<void> loadSvg() async {
    var svgDelete = await rootBundle.loadString(ImgR.imgBgDeleteIcon);
    final svg.PictureInfo pictureInfoDelete = await svg.vg.loadPicture(
        svg.SvgStringLoader(
          svgDelete,
        ),
        null);

    var svgLock = await rootBundle.loadString(ImgR.imgBgLockIcon);
    final svg.PictureInfo pictureInfoLock = await svg.vg.loadPicture(
        svg.SvgStringLoader(
          svgLock,
        ),
        null);

    var svgRotate = await rootBundle.loadString(ImgR.imgBgRotateIcon);
    final svg.PictureInfo pictureInfoRotate = await svg.vg.loadPicture(
        svg.SvgStringLoader(
          svgRotate,
        ),
        null);
    var svgScale = await rootBundle.loadString(ImgR.imgBgScaleIcon);
    final svg.PictureInfo pictureInfoScale = await svg.vg.loadPicture(
        svg.SvgStringLoader(
          svgScale,
        ),
        null);

    var svgUnlock = await rootBundle.loadString(ImgR.imgBgUnlock);
    final svg.PictureInfo pictureInfoUnlock = await svg.vg.loadPicture(
        svg.SvgStringLoader(
          svgUnlock,
        ),
        null);
    iconSvgLockList = [];
    iconSvgUnLockList = [];

    setState(() {
      iconSvgLockList.addAll([
        pictureInfoDelete,
        pictureInfoLock,
        pictureInfoRotate,
        pictureInfoScale,
      ]);
      iconSvgUnLockList.addAll([
        pictureInfoDelete,
        pictureInfoUnlock,
        pictureInfoRotate,
        pictureInfoScale,
      ]);
    });
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    loadImg();
    loadSvg();
    SystemChrome.setPreferredOrientations(// 使设备横屏显示
        [DeviceOrientation.landscapeLeft, DeviceOrientation.landscapeRight]);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Stack(
      children: [
        Listener(
          onPointerUp: (details) {
            eventType = null;
          },
          onPointerDown: (details) {
            // 获取点击的位置
            final position = details.position;
            startPosition = position;
            // 循环把图片都加上点击事件，判断当前的点击索引
            actionPictureList.forEach((actionPture) {
              for (var element in actionPture.rectList) {
                if (element.path != null) {
                  if (element.path!.contains(position)) {
                    print(
                        "循环列表的index：${element.currentIndex}，以及当前的index：${currentIndex}");
                    if (element.currentIndex != null &&
                        element.currentIndex != currentIndex) {
                      currentIndex = element.currentIndex!;
                      // 把当前的设置的组件放到最底部
                      // ActionPicture item =
                      //     actionPictureList.removeAt(currentIndex);
                      // actionPictureList.add(item);
                      setState(() {});
                      return;
                    }
                  }
                }
              }
            });

            currentActionPture.saveLastMatrix();
            // if (composeData != null) {
            //   for (var item in actionPictureList) {
            //     item.saveLastMatrix();
            //   }
            // }

            // 循环矩形点击域，添加点击事件
            for (var element in currentActionPture.rectList) {
              if (element.path != null) {
                if (element.path!.contains(position)) {
                  eventType = element.type;
                  // debugPrint("element event ：${element.type}");
                  if (eventType == CanvasEventType.image) {
                    print("当前的索引${element.currentIndex}");
                    currentIndex = element.currentIndex!;
                  } else if (eventType == CanvasEventType.scale) {
                  } else if (eventType == CanvasEventType.lock) {
                    currentActionPture.isLock = !currentActionPture.isLock;
                    setState(() {});
                  } else if (eventType == CanvasEventType.rotate) {
                    currentActionPture.updateCenterOffset();
                  } else if (eventType == CanvasEventType.delete) {
                    print("删除");
                    actionPictureList.removeAt(currentIndex);
                    setState(() {});
                  }
                  break;
                }
              }
            }
          },
          onPointerMove: (details) {
            // 获取移动的位置
            final position = details.position;
            // 移动开始前的点位减去移动时的点位，计算出偏移量
            final boxPosition = position - startPosition;

            if (eventType == CanvasEventType.image) {
              print("$boxPosition");
              currentActionPture.addTranslate(boxPosition);
              // if (composeData != null) {
              //   for (var item in actionPictureList) {
              //     item.addTranslate(boxPosition);
              //   }
              // }
              // matrix4 = (Matrix4.identity()
              //       ..translate(boxPosition.dx, boxPosition.dy)) *
              //     lastMatrix4.clone();

              setState(() {});
            } else if (eventType == CanvasEventType.scale) {
              // 这里把上一次的缩放值放回去了

              double currentScaleX =
                  (currentActionPture.imgSize.width + boxPosition.dx) /
                      currentActionPture.imgSize.width;
              double currentScaleY =
                  (currentActionPture.imgSize.height + boxPosition.dy) /
                      currentActionPture.imgSize.height;
              if (currentActionPture.isLock) {
                // 等比
                double equalScale = (currentScaleX + currentScaleY) / 2;
                currentScaleX = equalScale;
                currentScaleY = equalScale;
              }
              currentActionPture.addScale(currentScaleX, currentScaleY);
              // if (composeData != null) {
              //   for (var item in actionPictureList) {
              //     print("当前缩放的值：${currentScaleX},${currentScaleX}");
              //     item.addScale(currentScaleX, currentScaleY);
              //   }
              // }
              setState(() {});
              // matrix4 = lastMatrix4.clone()
              //   ..scale(currentScaleX, currentScaleY);
              // setState(() {});
            } else if (eventType == CanvasEventType.rotate) {
              // 求出初始坐标跟移动坐标后的方位角
              final angle = math.atan2(boxPosition.dy, boxPosition.dx);
              currentActionPture.addRotation(angle);
              setState(() {});
              // matrix4 = (Matrix4.identity()
              //       ..translate(newCenterOffset.dx, newCenterOffset.dy)
              //       ..rotateZ(angle)
              //       ..translate(-newCenterOffset.dx, -newCenterOffset.dy)) *
              //     lastMatrix4.clone();
              //
              // setState(() {});
            }
          },
          child: RepaintBoundary(
            child: CustomPaint(
              size: Size.infinite,
              painter: MyCustomPainter(
                  iconSvgLockList: iconSvgLockList,
                  composeData: composeData,
                  currentIndex: currentIndex,
                  iconSvgUnLockList: iconSvgUnLockList,
                  actionPictureList: actionPictureList),
            ),
          ),
        ),
        Positioned(
          top: 30,
          left: 30,
          child: GestureDetector(
            onTap: () {
              Get.back();
            },
            child: Container(
              padding: const EdgeInsets.all(10),
              decoration: BoxDecoration(
                  color: Colors.black26,
                  borderRadius: BorderRadius.circular(40)),
              child: const Icon(
                Icons.arrow_back,
                color: Colors.yellowAccent,
                size: 18,
              ),
            ),
          ),
        ),
        Positioned(
          top: 30,
          right: 260,
          child: GestureDetector(
            onTap: () {
              if (actionPictureList.length < 2) {
                AppToast.showText("请添加至2个或以上再操作");
              }
              // 生成两个盒子的矩形，然后把合并操作的id传进去idList，
              // 操作的时候，判断如果是合并操作，循环数组，把两个数组里的矩阵一起计算
              List<double> xList = [];
              List<double> yList = [];
              composeData = MatrixComposeModel(
                composeIdList: [],
                composePictureData: null,
              );
              for (int i = 0; i < actionPictureList.length; i++) {
                var item = actionPictureList[i];
                List<Offset> _offset = item.getCurrentVertex();
                for (Offset item in _offset) {
                  xList.add(item.dx);
                  yList.add(item.dy);
                }
                composeData!.composeIdList.add(i);
              }
              xList.sort();
              yList.sort();
              print("当前坐标list:${xList},${yList}");
              Size composeSize = Size(
                xList.last - xList.first,
                yList.last - yList.first,
              );
              ActionPicture composePicture = ActionPicture.initActionPicture(
                  initImgSvgPicture: null,
                  initMatrixData: Matrix4DataModel(
                      dx: xList.first,
                      dy: yList.first,
                      scaleX: 1,
                      scaleY: 1.0,
                      skewX: 0.0,
                      skewY: 0.0,
                      rotationAngle: 0.0),
                  initImgSize: composeSize);
              composeData?.composePictureData = composePicture;
              print("合并操作的盒子：${composeSize}");
              setState(() {});
            },
            child: Container(
              padding: const EdgeInsets.all(10),
              decoration: BoxDecoration(
                  color: Colors.black26,
                  borderRadius: BorderRadius.circular(40)),
              child: const Text('合并2个处理'),
            ),
          ),
        ),
        Positioned(
          top: 30,
          right: 170,
          child: GestureDetector(
            onTap: () {
              Matrix4DataModel data =
                  CanvasUtils.matrix4ToData(currentActionPture.matrix4);
              print("${data.toJson()}");
              setState(() {});
            },
            child: Container(
              padding: const EdgeInsets.all(10),
              decoration: BoxDecoration(
                  color: Colors.black26,
                  borderRadius: BorderRadius.circular(40)),
              child: const Text('矩阵解析'),
            ),
          ),
        ),
        Positioned(
          top: 30,
          right: 80,
          child: GestureDetector(
            onTap: () async {
              var mySvg = await rootBundle.loadString(ImgR.imgBgMyFill);
              final svg.PictureInfo pictureInfo1 = await svg.vg.loadPicture(
                  svg.SvgStringLoader(
                    mySvg,
                  ),
                  null);
              //初始化对象
              ActionPicture actionPicture = ActionPicture.initActionPicture(
                  initImgSvgPicture: pictureInfo1,
                  initImgSize: Size(100, 100),
                  initMatrixData: Matrix4DataModel(
                      dx: actionPictureList.length + 1 * 100,
                      dy: 100,
                      scaleX: 1,
                      scaleY: 1,
                      rotationAngle: 0,
                      skewX: 0.0,
                      skewY: 0.0));
              actionPictureList.add(actionPicture);
              currentIndex = actionPictureList.length - 1;
              setState(() {});
            },
            child: Container(
              padding: const EdgeInsets.all(10),
              decoration: BoxDecoration(
                  color: Colors.black26,
                  borderRadius: BorderRadius.circular(40)),
              child: const Text('添加元素'),
            ),
          ),
        ),
      ],
    ));
  }
}

class MyCustomPainter extends CustomPainter {
  MyCustomPainter({
    this.composeData,
    required this.currentIndex,
    required this.iconSvgLockList,
    required this.iconSvgUnLockList,
    required this.actionPictureList,
  });

  final MatrixComposeModel? composeData;
  final int currentIndex;
  List<svg.PictureInfo> svgIconList = [];
  List<svg.PictureInfo> iconSvgLockList;
  List<svg.PictureInfo> iconSvgUnLockList;
  List<ActionPicture> actionPictureList;

  // final CanvasEventType? eventType;

  @override
  void paint(Canvas canvas, Size size) {
    Paint paint = Paint();
    CanvasUtils.drawGrid(canvas, paint, size);
    CanvasUtils.drawCoor(canvas, paint, size);
    List.generate(actionPictureList.length, (index) {
      ActionPicture actionPicture = actionPictureList[index];
      svgIconList = actionPicture.isLock ? iconSvgLockList : iconSvgUnLockList;
      // TODO: implement paint
      actionPicture.rectList.clear();
      Rect imgRect = Rect.fromLTWH(
          0, 0, actionPicture.imgSize.width, actionPicture.imgSize.height);

      canvas.save();
      canvas.transform(actionPicture.matrix4.storage);
      if (actionPicture.imgSvgPicture != null) {
        // 绘制企鹅 svg  尺寸是imgSize
        CanvasUtils.drawResizeSvg(canvas, actionPicture.imgSvgPicture!.picture,
            actionPicture.imgSize, actionPicture.imgSvgPicture!.size,
            color: null);
      }
      canvas.restore();

      // 绘制操作
      drawAction(
          canvas: canvas,
          paint: paint,
          showAction: composeData == null ? currentIndex == index : false,
          actionPicture: actionPicture,
          index: index);
    });
    if (composeData != null) {
      ActionPicture actionPicture = composeData!.composePictureData!;
      svgIconList = actionPicture.isLock ? iconSvgLockList : iconSvgUnLockList;
      // TODO: implement paint
      actionPicture.rectList.clear();
      Rect imgRect = Rect.fromLTWH(
          0, 0, actionPicture.imgSize.width, actionPicture.imgSize.height);

      canvas.save();

      canvas.transform(actionPicture.matrix4.storage);

      canvas.save();

      CanvasUtils.drawResizeSvg(
          canvas,
          actionPictureList[0].imgSvgPicture!.picture,
          actionPictureList[0].imgSize,
          actionPictureList[0].imgSvgPicture!.size,
          color: null);

      canvas.restore();

      canvas.drawRect(
          imgRect,
          paint
            ..style = PaintingStyle.stroke
            ..color = Colors.red);
      // if (actionPicture.imgSvgPicture != null) {
      // 绘制企鹅 svg  尺寸是imgSize
      // CanvasUtils.drawResizeSvg(canvas, actionPicture.imgSvgPicture!.picture,
      //     actionPicture.imgSize, actionPicture.imgSvgPicture!.size,
      //     color: null);
      // }
      canvas.restore();

      // 绘制操作
      drawAction(
          canvas: canvas,
          paint: paint,
          showAction: true,
          actionPicture: actionPicture,
          index: 0);
    }
  }

  drawAction({
    required Canvas canvas,
    required Paint paint,
    required bool showAction,
    required ActionPicture actionPicture,
    required int index,
  }) {
    canvas.save();
    // 计算四个顶点的当前位置
    List<Offset> vertext = CanvasUtils.getVertex(
        imgSize: actionPicture.imgSize, matrix: actionPicture.matrix4);

    // 把给点位坐标添加命名
    TransformVertexModel transformVertex = TransformVertexModel(
      topLeft: vertext[0],
      topRight: vertext[1],
      bottomRight: vertext[2],
      bottomLeft: vertext[3],
    );

    // 获取dx，dy的值
    Matrix4DataModel matrix4Data =
        CanvasUtils.matrix4ToData(actionPicture.matrix4);

    // 绘制图片的矩形操作框
    Path imgTapPath = Path()..moveTo(vertext[0].dx, vertext[0].dy); // 移动到第一个顶点
    for (int i = 1; i < vertext.length; i++) {
      imgTapPath.lineTo(vertext[i].dx, vertext[i].dy); // 添加线段
    }
    imgTapPath.close(); // 封闭路径
    //把dx dy 偏移量加回去
    // debugPrint("矩阵变换后的盒子${imgTapPath.getBounds().center}");

    imgTapPath = imgTapPath.shift(Offset(matrix4Data.dx, matrix4Data.dy));
    // 绘制矩形
    paint
      ..color = Colors.orangeAccent
      ..style = PaintingStyle.stroke
      ..strokeWidth = 2.0;
    // canvas.translate(50, 200);
    canvas.drawPath(imgTapPath, paint);

    actionPicture.rectList.add(RectInfoModel(
        currentIndex: index,
        rect: Rect.zero,
        path: imgTapPath,
        type: CanvasEventType.image));

    // 绘制一个不旋转的矩形
    Rect centerToRect = imgTapPath.getBounds();

    canvas.drawRect(centerToRect, paint..color = Colors.purple);

    if (svgIconList.isNotEmpty && showAction) {
      drawActionIcon(
          canvas: canvas,
          paint: paint,
          eventType: CanvasEventType.scale,
          vertex: transformVertex.bottomRight,
          svgIcon: svgIconList[3],
          iconSize: actionPicture.iconSize,
          rectList: actionPicture.rectList,
          matrix4Data: matrix4Data);

      drawActionIcon(
          canvas: canvas,
          paint: paint,
          eventType: CanvasEventType.rotate,
          vertex: transformVertex.topRight,
          svgIcon: svgIconList[2],
          iconSize: actionPicture.iconSize,
          rectList: actionPicture.rectList,
          matrix4Data: matrix4Data);

      drawActionIcon(
          canvas: canvas,
          paint: paint,
          eventType: CanvasEventType.lock,
          vertex: transformVertex.topLeft,
          svgIcon: svgIconList[1],
          iconSize: actionPicture.iconSize,
          rectList: actionPicture.rectList,
          matrix4Data: matrix4Data);

      drawActionIcon(
        canvas: canvas,
        paint: paint,
        eventType: CanvasEventType.delete,
        vertex: transformVertex.bottomLeft,
        svgIcon: svgIconList[0],
        iconSize: actionPicture.iconSize,
        rectList: actionPicture.rectList,
        matrix4Data: matrix4Data,
      );
    }

    canvas.restore();
  }

  drawActionIcon({
    required Canvas canvas,
    required Paint paint,
    required CanvasEventType eventType,
    required svg.PictureInfo svgIcon,
    required Offset vertex,
    required Matrix4DataModel matrix4Data,
    required Size iconSize,
    required List<RectInfoModel> rectList,
  }) {
    canvas.save();
    Matrix4 iconRotateMatrix = Matrix4.identity()
      ..rotateZ(matrix4Data.rotationAngle);
    // 绘制右上角缩放的操作按钮
    Path iconPath;
    iconPath = Path()..moveTo(0, 0); // 移动到第一个顶点
    if (eventType == CanvasEventType.scale) {
      iconPath
        ..relativeLineTo(30, 0)
        ..relativeLineTo(0, 30)
        ..relativeLineTo(-30, 0);
    } else if (eventType == CanvasEventType.rotate) {
      iconPath
        ..relativeLineTo(30, 0)
        ..relativeLineTo(0, -30)
        ..relativeLineTo(-30, 0);
    } else if (eventType == CanvasEventType.lock) {
      iconPath
        ..relativeLineTo(-30, 0)
        ..relativeLineTo(0, -30)
        ..relativeLineTo(30, 0);
    } else {
      iconPath
        ..relativeLineTo(-30, 0)
        ..relativeLineTo(0, 30)
        ..relativeLineTo(30, 0);
    }

    iconPath.close(); // 封闭路径

    //旋转icon
    iconPath = iconPath.transform(iconRotateMatrix.storage);
    //把dx dy 偏移量加回去
    iconPath = iconPath
        .shift(Offset(matrix4Data.dx + vertex.dx, matrix4Data.dy + vertex.dy));

    paint
      ..color = Colors.red
      ..style = PaintingStyle.stroke
      ..strokeWidth = 2.0;

    canvas.drawPath(
        iconPath,
        paint
          ..style = PaintingStyle.fill
          ..color = Colors.black45);

    canvas.translate(iconPath.getBounds().center.dx - iconSize.width / 2 + 5,
        iconPath.getBounds().center.dy - iconSize.height / 2 + 5);
    CanvasUtils.drawResizeSvg(
        canvas, svgIcon.picture, const Size(20, 20), svgIcon.size,
        color: Colors.white);
    rectList
        .add(RectInfoModel(rect: Rect.zero, path: iconPath, type: eventType));
    canvas.restore();
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    // TODO: implement shouldRepaint
    return true;
  }
}
